package com.basic.java.threads.implRunnable;

/**
 * 龟兔赛跑类模拟龟兔赛跑
 * <p>
 * 创建时间：2022/4/13 23:22
 *
 * @author gejin
 */
public class Race implements Runnable {
    private static String winner; // 定义一个赢家

    @Override
    public void run() {
        for (int i = 0; i <= 1000; i++) { // 假设跑1000米的路程
            if (Thread.currentThread().getName().equals("兔子") && i % 100 == 0) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            boolean flag = gameOver(i);
            if (flag) {
                break;
            }
            System.out.println(Thread.currentThread().getName() + "---->跑了" + i + "步");
        }
    }

    /**
     * 判断是否结束比赛
     *
     * @param steps 跑的步数
     * @return boolean
     */
    private boolean gameOver(int steps) {
        if (winner != null) { // 如果赢家不为null， 返回true
            return true;
        }
        {
            if (steps >= 1000) { // 如果步数大于等于1000， 输出赢家并返回true
                winner = Thread.currentThread().getName();
                System.out.println("winner is---->" + winner);
                return true;
            }

        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();
    }
}
